// Copyright (c) Microsoft Corporation. All rights reserved.

using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation;
using Microsoft.TeamFoundation.Migration.Toolkit;
using Microsoft.TeamFoundation.Migration.Toolkit.VC;
using Microsoft.TeamFoundation.VersionControl.Common;

namespace Microsoft.Vsts.Rangers.Migration.TfsToTfs
{
    internal static class Util
    {
        public static VersionControlMapping FindAppropriateMappingForServerPath(string serverPath, VersionControlSession session)
        {
            if (string.IsNullOrEmpty(serverPath))
            {
                throw new ArgumentNullException("serverPath");
            }
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            
            VersionControlMapping mostSpecificMapping = null;

            foreach (VersionControlMapping current in session.Mappings)
            {
                if (VersionControlPath.IsSubItem(serverPath, current.Source))
                {
                    // if it's the first option we've seen or if the mapping is more specific than
                    // the previously most specific - make it the most specific
                    if (mostSpecificMapping == null ||
                        VersionControlPath.IsSubItem(current.Source, mostSpecificMapping.Source))
                    {
                        mostSpecificMapping = current;
                    }
                }
            }

            if (mostSpecificMapping != null)
            {
                return mostSpecificMapping.Cloak ? null : mostSpecificMapping;
            }

            return null;
        }


        /// <summary>
        /// Reverse a given mappings
        /// [source, target]->[target,source]
        /// [source, cloak>->[target,cloak]
        /// [target, cloak]->[source,cloak>
        /// </summary>
        /// <param name="mappings"></param>
        /// <returns></returns>
        internal static Collection<VersionControlMapping> ReverseVersionControlMappings(Collection<VersionControlMapping> mappings)
        {
            if (null == mappings)
                return null;

            Collection<VersionControlMapping> reversedMappings = new Collection<VersionControlMapping>();
            foreach (VersionControlMapping mapping in mappings)
            {
                VersionControlMapping reversedMapping = new VersionControlMapping();
                reversedMapping.Source = mapping.Target;
                reversedMapping.Target = mapping.Source;
                reversedMapping.Cloak = mapping.Cloak;
                reversedMappings.Add(reversedMapping);
            }
            return reversedMappings;
        }
    }
}
